<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use Exception;
use think\Db;
use XznsTools\cache\CacheManage;

/**
 * 日运设置模型
 * Class FortuneSetting
 * @package app\common\cachemodel
 */
class FortuneSetting extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_fortune_setting';
    protected $cacheModel = 'fortune.fortune_day_setting';

    /**
     * 添加日记
     * @param $uid
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function SaveData($uid, $data)
    {
        $time = time();
        $data['create_time'] = $time;
        try
        {
            $this->save($data);
        }
        catch (Exception $e)
        {
            $this->error = '添加笔记失败';
            return false;
        }
        // 添加日记缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)
            ->setCache($data, 'details', false);
        return true;
    }

    /**
     * 更新日记
     * @param $uid
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function UpdateData($uid, $data)
    {
        $time = time();
        $data['update_time'] = $time;
        try
        {
            $this->where(['uid' => $uid])->update($data);
        }
        catch (Exception $e)
        {
            $this->error = '更新笔记失败';
            return false;
        }
        // 添加日记缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)
            ->setCache($data, 'details', true);
        return true;
    }

    /**
     * 缓存获取用户日运配置信息
     * @param $uid
     * @return array|bool|string
     * @throws Exception
     */
    public function FortuneSetting($uid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)
            ->getCache('name');

        if ($data === false)
        {
            $data = $this->FortuneSettingFromDms($uid);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCache($data);
        }
        return $data;
    }

    /**
     * 数据库获取用户运势配置
     * @param $uid
     * @return array
     */
    public function FortuneSettingFromDms($uid)
    {
        $where = ['uid' => $uid];
        try
        {
            $arr = Db::table('app_fortune_setting')
                ->where($where)
                ->column('id,uid,status,name,create_time,update_time', 'id');

            if (!$arr)
            {
                $arr = Db::table('app_fortune_setting')
                    ->where('uid', 0)
                    ->column('id,uid,status,name,create_time,update_time', 'id');
            }

            $arr = current($arr);
        }
        catch (Exception $e)
        {
            $arr = [];
        }

        return $arr;
    }
}